<template>
  <div v-loading="loading" class="order-handle">
    <el-dialog v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.2)" :visible.sync="dialogShow" title="订单处理" width="800px" :close-on-click-modal="false" @close="handleBack">
      <c-form-container :column="1" :bottom="false">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="140px">
          <el-form-item prop="payResult" label="打款结果:">
            <div>{{ formaterData(payResultList, formData.payResult) }}</div>
          </el-form-item>
          <el-form-item prop="demandResultHandle" label="打款结果处理:">
            <el-select v-if="formData.payResult === 'GIVEUP_REMIT'" v-model="formData.demandResultHandle" placeholder="请选择打款结果处理" style="width:100%" @change="changeDesign">
              <el-option v-for="item in isAgreeList" :key="item.dictCode" :label="item.dictName" :value="item.dictCode" />
            </el-select>
            <el-select v-else v-model="formData.demandResultHandle" placeholder="请选择打款结果处理" style="width:100%" @change="changeResult">
              <el-option v-for="item in agreeList" :key="item.dictCode" :label="item.dictName" :value="item.dictCode" />
            </el-select>
            <!-- <c-dict-select v-if="formData.payResult === 'GIVEUP_REMIT'" v-model="formData.demandResultHandle" dict-type-code="REVIEW_RESULT" placeholder="打款结果处理" clearable />
            <c-dict-select v-else v-model="formData.demandResultHandle" dict-type-code="DEMAND_RESULT_HANDLE" placeholder="打款结果处理" clearable /> -->
          </el-form-item>
          <el-form-item
            prop="demandReviewAdvice"
            label="打款结果审核意见:"
            :rules="[{ required: (formData.payResult === 'GIVEUP_REMIT' || formData.demandResultHandle === 'ORDER_FAILE'), message: '请输入打款结果审核意见' }]"
          >
            <el-input v-model="formData.demandReviewAdvice" type="textarea" :autosize="{minRows:3}" placeholder="打款结果审核意见" clearable />
          </el-form-item>
          <el-form-item v-if="showKD" prop="reason" label="订单号:">
            <table-box
              ref="orderCodeTable"
              :off-set="-20"
              :data="tableData"
              :table-config="tableConfig"
              :table-max-height="200"
              @btnOperate="btnOperate"
            >
              <!-- <el-table-column prop="poCode" label="采购订单号" sortable min-width="100">
                <template slot-scope="scope">
                  <el-input ref="materialInput" v-model.trim="scope.row.poCode" size="mini" placeholder="请输入采购订单号" maxlength="128" @blur="checkDetailItemPo(scope.row)" />
                </template>
              </el-table-column> -->
              <el-table-column prop="soCode" label="销售订单号" sortable min-width="100">
                <template slot-scope="scope">
                  <el-input ref="materialInput" v-model.trim="scope.row.soCode" size="mini" placeholder="请输入销售订单号" maxlength="128" @blur="checkDetailItemSo(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column prop="orderDesc" label="说明" sortable min-width="100">
                <template slot-scope="scope">
                  <el-input ref="materialInput" v-model="scope.row.orderDesc" size="mini" placeholder="请输入说明" maxlength="128" />
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="handleDel(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </table-box>
            <!-- <c-table-box :table-max-height="200" :data="formData.orderCodes" :index="false" :table-config="tableConfig" /> -->
          </el-form-item>
          <el-form-item v-if="showKD" label="开单明细附件:">
            <div v-for="item in fileTypeList" :key="item.id">
              <div class="qup-title-box">
                <span class="border" /><span>附件上传-{{ item.attachmentType }}</span>
              </div>
              <file-uploader
                :data="item.fileList"
                :file-type="item.fileTypeName"
                :config-attachment-id="item.id"
                :limit="20"
                @remove="removeFile"
                @upload-success="uploadSuccessFile"
              />
            </div>
          </el-form-item>
          <!-- <el-form-item>
            <div>
              <el-button type="primary" @click="confirmHandle">确定</el-button>
              <el-button type="primary" @click="handleBack">取消</el-button>
            </div>
          </el-form-item> -->
        </el-form>
      </c-form-container>
      <div slot="footer">
        <el-button size="mini" @click="handleBack">取消</el-button>
        <el-button type="primary" size="mini" @click="confirmHandle">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { postConfigAttachmentTemplate, getProConfigEditData, changeFileList, changeConfigState } from '@/api/proConfig'
import { getDictByPatchType } from '@/api/dataDict'
import fileUploader from '@/components/importFile'
import { getShopAttachment } from '@/api/decorate'
export default {
  name: 'Remit',
  components: {
    fileUploader
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      showKD: false,
      accountName: '',
      payResultList: [],
      demandResultList: [],
      resultHandleList: [],
      isAgreeList: [],
      agreeList: [],
      tableData: [],
      formData: {
        payResult: '',
        handleResult: '',
        reason: '',
        orderCodes: []
      },
      formRules: {},
      tableConfig: {
        hideSearchBar: true,
        btnList: [{
          buttonName: '新增',
          optCode: 'add',
          outerFlag: true
        }]
      }
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  created() {
    this.formData.id = this.detailData.id
    getProConfigEditData(this.formData.id).then(res => {
      if (res.success && res.data) {
        this.formData = res.data
        this.tableData = this.formData.productConfigOrderDtos
      }
    })
    this.getDictByPatchTypeAll(['PAY_RESULT', 'DEMAND_RESULT_HANDLE'])
      .then(res => {
        this.payResultList = res.PAY_RESULT
        this.resultHandleList = res.DEMAND_RESULT_HANDLE
        this.isAgreeList = this.resultHandleList.filter(item => item.dictName === '同意' || item.dictName === '退回上一节点')
        this.agreeList = this.resultHandleList.filter(item => item.dictName === '已开单' || item.dictName === '退回上一步')
      })
    postConfigAttachmentTemplate('PRODUCT_CONFIG').then(res => {
      if (res.success === 1) {
        // 根据modelId获取每个配置id
        if (res.data && res.data.records) {
          this.fileTypeList = res.data.records.filter(item => item.attachmentType === '开单明细附件')
          this.fileTypeList.forEach(row => {
            this.$set(row, 'fileList', [])
          })
        }
      }
    })
  },
  methods: {
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      if (!arr) return
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    // 选择打款结果处理
    changeResult(value) {
      if (value === 'ORDER_SUCC') {
        this.showKD = true
        return
      }
      this.showKD = false
    },
    // 按钮组
    btnOperate(flag) {
      switch (flag) {
        case 'add':
          this.addRow()
          break
        default:
          break
      }
    },
    // checkDetailItemPo(row) {
    //   const poCode = row.poCode
    //   const soCode = row.soCode
    //   const flag = this.tableData.filter(item => ((item.poCode.length && item.poCode === poCode) && (item.soCode.length && item.soCode === soCode)))
    //   if (flag.length > 1) {
    //     this.$message.warning(`销售订单号${soCode}对应的采购订单号${poCode}已存在，请重新输入`)
    //     row.poCode = ''
    //   }
    // },
    checkDetailItemSo(row) {
      const poCode = row.poCode
      const soCode = row.soCode
      const flag = this.tableData.filter(item => ((item.poCode.length && item.poCode === poCode) && (item.soCode.length && item.soCode === soCode)))
      if (flag.length > 1) {
        this.$message.warning(`采购订单号${poCode}对应的销售订单号${soCode}已存在，请重新输入`)
        row.soCode = ''
      }
    },
    // 删除
    handleDel(row) {
      const index = this.tableData.findIndex(item => (item.poCode === row.poCode && item.soCode === row.soCode))
      if (index !== -1) {
        this.tableData.splice(index, 1)
      }
    },
    // 获取附件
    getFiles() {
      getShopAttachment(this.id).then(res => {
        this.fileTypeList.forEach(row => {
          row.fileList = res.data.filter(i => i.configAttachmentId === row.id)
        })
      })
    },
    removeFile() {},
    uploadSuccessFile() {},
    // 返回
    handleBack() {
      this.dialogShow = false
      this.clearForm()
      this.$emit('success')
    },
    clearForm(done) {
      this.formData = {
        constData: [],
        staff: []
      }
      this.$refs.rulesForm && this.$refs.rulesForm.clearValidate()
      done && done()
    },
    // 确认
    confirmHandle() {
      this.$refs.form.validate(validate => {
        if (validate) {
          if (this.formData.demandResultHandle === 'ORDER_SUCC' && !this.tableData.length) {
            this.$message.warning('请添加订单号')
            return
          }
          const arr = this.tableData.filter(item => !item.soCode)
          if (arr.length > 0) {
            this.$message.warning('请完善表格数据')
            return
          }
          const len = this.fileTypeList.map(item => item.fileList.length)
          if (this.formData.demandResultHandle === 'ORDER_SUCC') {
            if (!len[0]) {
              this.$message.warning('请至少上传一个开单明细附件')
              return
            }
          }
          this.loading = true
          const dtos = this.fileTypeList.map(item => item.fileList)
          dtos[0].forEach(file => {
            file.modelId = this.formData.id
          })
          changeFileList(dtos[0], this.formData.id).then(res => {
            if (res.success) {
              changeConfigState(this.formData).then(res => {
                if (res.success) {
                  this.$message.success('操作成功')
                  this.clearForm()
                  this.dialogShow = false
                  this.$emit('success', false)
                }
                this.loading = false
              }).catch(() => {
                this.loading = false
              })
            }
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    // removeRow(row) {
    //   this.formData.orderCodes.splice(row.keyIndex, 1)
    // },
    addRow() {
      this.tableData.push({
        poCode: '',
        soCode: '',
        orderDesc: ''
      })
    },
    openedHandle() {
      if (this.formData.orderCodes.length === 0) {
        this.addRow()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.order-handle{
  display: inline-block;
  margin: 0 10px;
}
</style>
